package cn.gz.lbs.glsc;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import com.netnewera.l1.ans.Ans;
import com.netnewera.l1.report.Report;
import com.netnewera.l1.req.Client;
import com.netnewera.l1.req.GeoInfo;
import com.netnewera.l1.req.Lir;
import com.netnewera.l1.req.Msids;
import com.netnewera.l1.req.Originator;
import com.netnewera.l1.req.Req;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import cn.gz.lbs.entity.LirNeedEntity;
import cn.gz.zoomtech.common.ConfManager;

import test.Test;

public class GLSCProxy {
	
	private static final Logger log = Logger.getLogger(GLSCProxy.class);
	private static CompositeConfiguration cf = ConfManager.getInstance().getConf();

	/**
	 * package_name: cn.gz.lbs.main
	 * file_name:    GLSCProxy.java
	 * description: 
	 * 2013-6-27下午5:42:17
	 * Author: chenhui
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	
	/**
	 * 
	* package_name: cn.gz.lbs.glsc
	* file_name:    GLSCProxy.java
	* description: 单个请求号码的处理
	*              请求转换获取响应（将SP的请求转换成LBSC对GLSC的请求，并将GLSC的响应转换成给SP的响应）
	* 2013-7-9下午3:40:05
	* Author: chenhui
	 * @param reqObject
	 * @return Ans
	 */
	public Ans reqFromLbscToGLSC(Req reqObject) {
		
		HttpPost httppost = null;
		
		String headStr = "<?xml version=\"1.0\"?><!DOCTYPE REQ SYSTEM \"LOCREQ.DTD\">";
		String respStr = null;
		
		String respHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE ANS SYSTEM \"LOCANS.DTD\">";
//		<?xml version="1.0" encoding="UTF-8"?>
//		<!DOCTYPE ANS SYSTEM "LOCANS.DTD">
//		<ANS VER="1.0.0">
//		  <LCSCLIENTID>1055100</LCSCLIENTID>
//		  <ORID>15675515759</ORID>
//		  <LIA>
//		    <RESULT>0</RESULT>
//		    <POSINFOS>
//		      <POSINFO>
//		        <POSITIONRESULT>1</POSITIONRESULT>
//		        <MSID>15675515759</MSID>
//		        <MSID_TYPE>0</MSID_TYPE>
//		        <AREACODE>10</AREACODE>
//		        <LOCALTIME>20130722145354</LOCALTIME>
//		        <LATITUDETYPE>1</LATITUDETYPE>
//		        <LATITUDE>314837.174</LATITUDE>
//		        <LONGITUDETYPE>0</LONGITUDETYPE>
//		        <LONGITUDE>1171228.022</LONGITUDE>
//		        <RADIUS>0</RADIUS>
//		        <POSOUR>6</POSOUR>
//		        <ROAMCITY>551</ROAMCITY>
//		      </POSINFO>
//		    </POSINFOS>
//		  </LIA>
//		</ANS>
		Ans respAns = null;
		
        XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
		try {
			// *****************************************************************
			xStream.autodetectAnnotations(true);
			
			HttpClient httpclient = new DefaultHttpClient();

			String serverUrl = cf.getString("GLSC_ServerURL",
					"http://192.168.1.141:80/glsc/LbsProxyServer");
			
//			step1: 将SP的请求对象转换成LBSC的请求对象（替换鉴权账号等）
			String sp_clientID = reqObject.getClient().getLcsclientid();
			String sp_orid = reqObject.getOriginator().getOrid();
			
			String lbsc_clientID=cf.getString("lbsc_clientID","1055100");
			String lbsc_password=cf.getString("lbsc_password","1055100");
//            String lbsc_orid=cf.getString("lbsc_orid","1055100");
         	String lbsc_oridType=cf.getString("lbsc_oridType","0");
            String lbsc_serviceID=cf.getString("lbsc_serviceID","ahzxt");
			 
    		Client client = new Client();
    		client.setLcsclientid(lbsc_clientID);
    		client.setPassword(lbsc_password);
    		reqObject.setClient(client);
    		
    		Originator originator = new Originator();
    		
    		Lir lirOne = (Lir)reqObject.getLir();
    		List msidList = lirOne.getMsids().getMsid();
    		String tel = (String)msidList.get(0);
    		
    		originator.setOrid(tel);
    		originator.setOridType(lbsc_oridType);
    		reqObject.setOriginator(originator);
    		
            reqObject.setServiceid(lbsc_serviceID);
            
//          step2: 将请求对象转换成请求字符串
            String reqBody = xStream.toXML(reqObject);
            String reqXml = headStr + reqBody;
            log.info("inProxy,glscReqIs:" + reqXml);
			httppost = new HttpPost(serverUrl);
			StringEntity myEntity = new StringEntity(reqXml, "utf-8");
			httppost.addHeader("Content-Type", "text/xml");
			httppost.setEntity(myEntity);
//			step3: 执行发起请求，并取得GLSC响应内容
			HttpResponse response = httpclient.execute(httppost);
			
			HttpEntity resEntity = response.getEntity();

			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "utf-8");
			char[] buff = new char[1024];
			int length = 0;
			String receivedStr = "";
			while ((length = reader.read(buff)) != -1) {
				receivedStr = receivedStr + new String(buff, 0, length);

			}
			respStr = receivedStr;
			log.info("inProxy,glscRespIs:" + respStr);
//			step4:解析总部GLSC返回的resp响应串，转换成LBSC 返回给SP的Ans对象
			 int firstKey = respStr.indexOf(">");
			 String respStrtemp = respStr.substring(firstKey+1);
			
			 int secondKey = respStrtemp.indexOf(">");			
			String respStrNoHead = respStrtemp.substring(secondKey+1); 
			
			log.debug("inProxy_respStrNoHead:" + respStrNoHead);
       
			xStream.alias("ANS",Ans.class);
			respAns = (Ans)xStream.fromXML(respStrNoHead);
			respAns.setLcsclientid(sp_clientID);
			respAns.setOrid(sp_orid);
//			将reqObject复原(有克隆方法之后，就不用了。)
			
			
			
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("errorInGLSCProxy,ex:",ex);
		}
		return respAns;
		
	}
	
	/**
	 * 
	* package_name: cn.gz.lbs.glsc
	* file_name:    GLSCProxy.java
	* description: 批量定位处理
	* 2013-8-10下午1:06:12
	* Author: chenhui
	 * @param reqObject
	 * @return Ans
	 */
	public Ans reqFromLbscToGLSCBatch(Req reqObject) {
		
		HttpPost httppost = null;
		
		String headStr = "<?xml version=\"1.0\"?><!DOCTYPE REQ SYSTEM \"LOCREQ.DTD\">";
		String respStr = null;
		
		String respHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE ANS SYSTEM \"LOCANS.DTD\">";

		Ans respAns = null;
		
        XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
		try {
			// *****************************************************************
			xStream.autodetectAnnotations(true);
			
			HttpClient httpclient = new DefaultHttpClient();

			String serverUrl = cf.getString("GLSC_ServerURL",
					"http://192.168.1.141:80/glsc/LbsProxyServer");
			
//			step1: 将SP的请求对象转换成LBSC的请求对象（替换鉴权账号等）
			String sp_clientID = reqObject.getClient().getLcsclientid();
			String sp_orid = reqObject.getOriginator().getOrid();
			
			String lbsc_clientID=cf.getString("lbsc_clientID","1055100");
			String lbsc_password=cf.getString("lbsc_password","1055100");
//            String lbsc_orid=cf.getString("lbsc_orid","1055100");
         	String lbsc_oridType=cf.getString("lbsc_oridType","0");
            String lbsc_serviceID=cf.getString("lbsc_serviceID","ahzxt");
			 
    		Client client = new Client();
    		client.setLcsclientid(lbsc_clientID);
    		client.setPassword(lbsc_password);
    		reqObject.setClient(client);
    		
    		Originator originator = new Originator();
    		
    		Lir lirOne = (Lir)reqObject.getLir();
    		List msidList = lirOne.getMsids().getMsid();
    		String tel = (String)msidList.get(0);
    		
    		originator.setOrid(tel);
    		originator.setOridType(lbsc_oridType);
    		reqObject.setOriginator(originator);
    		
            reqObject.setServiceid(lbsc_serviceID);
            
//          step2: 将请求对象转换成请求字符串
            String reqBody = xStream.toXML(reqObject);
            String reqXml = headStr + reqBody;
            log.info("inProxy,glscReqIs:" + reqXml);
			httppost = new HttpPost(serverUrl);
			StringEntity myEntity = new StringEntity(reqXml, "utf-8");
			httppost.addHeader("Content-Type", "text/xml");
			httppost.setEntity(myEntity);
//			step3: 执行发起请求，并取得GLSC响应内容
			HttpResponse response = httpclient.execute(httppost);
			
			HttpEntity resEntity = response.getEntity();

			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "utf-8");
			char[] buff = new char[1024];
			int length = 0;
			String receivedStr = "";
			while ((length = reader.read(buff)) != -1) {
				receivedStr = receivedStr + new String(buff, 0, length);

			}
			respStr = receivedStr;
			log.info("inProxy,glscRespIs:" + respStr);
//			step4:解析总部GLSC返回的resp响应串，转换成LBSC 返回给SP的Ans对象
			 int firstKey = respStr.indexOf(">");
			 String respStrtemp = respStr.substring(firstKey+1);
			
			 int secondKey = respStrtemp.indexOf(">");			
			String respStrNoHead = respStrtemp.substring(secondKey+1); 
			
			log.debug("inProxy_respStrNoHead:" + respStrNoHead);
       
			xStream.alias("ANS",Ans.class);
			respAns = (Ans)xStream.fromXML(respStrNoHead);
			respAns.setLcsclientid(sp_clientID);
			respAns.setOrid(sp_orid);
			
			
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("errorInGLSCProxy,ex:",ex);
		}
		return respAns;
		
	}
	
	/**
	 * 
	* package_name: cn.gz.lbs.glsc
	* file_name:    GLSCProxy.java
	* description: 向总部发起单次定位请求，此方法单独给周期定位定时任务用。
	* 2013-9-2下午4:20:47
	* Author: chenhui
	 * @param reqObject
	 * @return Ans
	 */
	public Ans reqToGLSCFromLtrrJob(LirNeedEntity entity) {
		
		HttpPost httppost = null;
		
		String headStr = "<?xml version=\"1.0\"?><!DOCTYPE REQ SYSTEM \"LOCREQ.DTD\">";
		String respStr = null;

		Ans respAns = null;
		
        XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
		try {
			// *****************************************************************
			xStream.autodetectAnnotations(true);
			
			HttpClient httpclient = new DefaultHttpClient();

			String serverUrl = cf.getString("GLSC_ServerURL",
					"http://192.168.1.141:80/glsc/LbsProxyServer");
//			step1: 将LirNeedEntity对象转换成LBSC的请求对象Req（替换鉴权账号等以及构造其他请求参数）
			Req reqObject = new Req();			
			
			String sp_clientID = entity.getLcsclientid();
			String sp_orid = entity.getOrid();
			
			String lbsc_clientID=cf.getString("lbsc_clientID","1055100");
			String lbsc_password=cf.getString("lbsc_password","1055100");
         	String lbsc_oridType=cf.getString("lbsc_oridType","0");
            String lbsc_serviceID=cf.getString("lbsc_serviceID","ahzxt");
//			构造Client
    		Client client = new Client();
    		client.setLcsclientid(lbsc_clientID);
    		client.setPassword(lbsc_password);
    		reqObject.setClient(client);
//    		构造Originator
    		Originator originator = new Originator();
    		originator.setOrid(entity.getMsid());
    		originator.setOridType(lbsc_oridType);
    		reqObject.setOriginator(originator);
    		
    		reqObject.setReqPlatform(entity.getReqPlatform());
            reqObject.setServiceid(lbsc_serviceID);
//          构造Lir
            Lir lir= new Lir();
    		lir.setPrio(entity.getPrio()); // 0:普通优先级处理； 1：高优先级处理
//            
            Msids msids = new Msids();
            
    		List<String> msid = new ArrayList<String>();
    		msid.add(entity.getMsid()); 
    		
    		msids.setMsid(msid);
    		msids.setMsidType(entity.getMsidType());
    		lir.setMsids(msids);
//    		曾补其他参数
    		lir.setOriguserAccessType(entity.getOriguserAccessType());
    		lir.setFindmeIndic(entity.getFindmeIndic());
    		lir.setPosreqtype(entity.getPosreqtype());
    		
//			新增：LL_FORMAT waitaa
			GeoInfo geoInfo = new GeoInfo();
			geoInfo.setCoordSys("LL"); // 经度纬度格式
	        geoInfo.setDatum("WGS-84"); // 全球大地测量系统 1984
	        geoInfo.setLlFormat("D5");
			
	        lir.setGeoInfo(geoInfo);
    		
    		reqObject.setLir(lir);
//          step2: 将请求对象转换成请求字符串
            String reqBody = xStream.toXML(reqObject);
            String reqXml = headStr + reqBody;
            log.info("inLtrrProxy,glscReqIs:" + reqXml);
			httppost = new HttpPost(serverUrl);
			StringEntity myEntity = new StringEntity(reqXml, "utf-8");
			httppost.addHeader("Content-Type", "text/xml");
			httppost.setEntity(myEntity);
//			step3: 执行发起请求，并取得GLSC响应内容
			HttpResponse response = httpclient.execute(httppost);
			
			HttpEntity resEntity = response.getEntity();

			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "utf-8");
			char[] buff = new char[1024];
			int length = 0;
			String receivedStr = "";
			while ((length = reader.read(buff)) != -1) {
				receivedStr = receivedStr + new String(buff, 0, length);

			}
			respStr = receivedStr;
			log.info("inLtrrProxy,glscRespIs:" + respStr);
//			step4:解析总部GLSC返回的resp响应串，转换成LBSC 返回给SP的Ans对象
			 int firstKey = respStr.indexOf(">");
			 String respStrtemp = respStr.substring(firstKey+1);
			
			 int secondKey = respStrtemp.indexOf(">");			
			String respStrNoHead = respStrtemp.substring(secondKey+1); 
			
			log.debug("inLtrrProxy_respStrNoHead:" + respStrNoHead);
       
			xStream.alias("ANS",Ans.class);
			xStream.alias("Report", Report.class);
			respAns = (Ans)xStream.fromXML(respStrNoHead);
			respAns.setLcsclientid(sp_clientID);
			respAns.setOrid(sp_orid);
			
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("errorLtrrProxy,ex:",ex);
		}
		return respAns;
		
	}

	/**
	 * 
	* package_name: cn.gz.lbs.glsc
	* file_name:    GLSCProxy.java
	* description: LBSC系统平台发起定位请求到总部GLSC，并取得响应结果。
	* 2013-7-9下午2:49:05
	* Author: chenhui
	 * @param reqStr
	 * @return 响应字符串
	 */
	public String requestByHttpClient(String reqStr) {

		String respStr = null;
		HttpPost httppost = null;
		
		try {
			log.info("IamGLSCProxy,reqStr_is:"+reqStr);
			// *****************************************************************
			HttpClient httpclient = new DefaultHttpClient();

			String serverUrl = cf.getString("GLSC_ServerURL",
					"http://192.168.1.141:80/glsc/LbsProxyServer");
			// String headStr =
			// "<?xml version=\"1.0\"?><!DOCTYPE REQ SYSTEM \"LOCREQ.DTD\">";
			//
			// String reqStr = headStr+Test.testLir();

			// test:

			// String noHeadReq = reqStr.replace(headStr, "");
			// System.out.println("noHeadReq:"+noHeadReq);
			// System.out.println("reqStr:"+reqStr);

			httppost = new HttpPost(serverUrl);

			StringEntity myEntity = new StringEntity(reqStr, "utf-8");
			httppost.addHeader("Content-Type", "text/xml");
			httppost.setEntity(myEntity);
			// 响应定义
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "utf-8");
			char[] buff = new char[1024];
			int length = 0;
			String receivedStr = "";
			while ((length = reader.read(buff)) != -1) {
				receivedStr = receivedStr + new String(buff, 0, length);

			}
			respStr = receivedStr;
			log.info("IamGLSCProxy,remoteRespIs:" + respStr);
			httpclient.getConnectionManager().shutdown();
			
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("errorInGLSCProxy,ex:",ex);
		}
		return respStr;
		
	}

}
